<script lang="ts" setup>
import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';
import type { RoutingModel, RoutingStepModel } from '#/api/process/models';

import { onMounted, ref, watchEffect } from 'vue';

import { Flex, InputSearch, List, ListItem } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getRoutingListApi } from '#/api/process/routing';
import { getRoutingStepListApi } from '#/api/process/routingStep';

defineOptions({
  inheritAttrs: false,
});

const emit = defineEmits<{
  (e: 'itemSelected', item?: RoutingStepModel): void;
}>();

const searchKey = ref('');
const routingIdSelected = ref(0);
const routingData = ref<RoutingModel[]>([]);
const routingFilterData = ref<RoutingModel[]>([]);

const gridOptions: VxeGridProps<RoutingStepModel> = {
  columns: [
    { type: 'seq', width: 60 },
    { field: 'operation.opCode', title: '工序', minWidth: 100 },
  ],
  border: true,
  rowConfig: {
    isHover: true,
    isCurrent: true,
  },
  pagerConfig: {
    enabled: false,
  },
};

const gridEvents: VxeGridListeners<RoutingStepModel> = {
  cellClick: ({ row }) => {
    emit('itemSelected', row);
  },
};

const [Grid, gridApi] = useVbenVxeGrid({ gridEvents, gridOptions });

async function loadData(routingId: number) {
  routingIdSelected.value = routingId;
  gridApi.setLoading(true);
  const data = await getRoutingStepListApi({ routingId });
  gridApi.grid.loadData(data);
  setTimeout(() => {
    gridApi.setLoading(false);
  }, 300);
  emit('itemSelected');
}

onMounted(async () => {
  routingData.value = await getRoutingListApi();
});

watchEffect(() => {
  routingFilterData.value = routingData.value.filter((s) =>
    s.routingName.includes(searchKey.value),
  );
});
</script>

<template>
  <Flex class="h-full w-full">
    <div class="h-full w-6/12">
      <List
        :data-source="routingFilterData"
        :split="false"
        bordered
        class="h-full overflow-auto"
        size="small"
      >
        <template #header>
          <div>
            <InputSearch
              v-model:value="searchKey"
              allow-clear
              placeholder="输入工艺路线"
              size="small"
            />
          </div>
        </template>
        <template #renderItem="{ item }">
          <ListItem>
            <div
              :class="[{ isActive: item.id === routingIdSelected }]"
              class="w-full cursor-pointer rounded-sm px-1"
              @click="loadData(item.id)"
            >
              {{ item.routingName }}
            </div>
          </ListItem>
        </template>
      </List>
    </div>
    <div class="ml-2 h-full w-6/12">
      <Grid />
    </div>
  </Flex>
</template>

<style scoped>
.isActive {
  background-color: #1890ff;
}
</style>
